package top.hepingan.java.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.hepingan.java.common.Result;
import top.hepingan.java.entity.Muser;
import top.hepingan.java.service.Impl.service.IMuserService;
import top.hepingan.java.utils.UserUtils;

@RequestMapping("/user")
@RestController
@Slf4j
@RequiredArgsConstructor
public class UserController {
    private final IMuserService userService;
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result register(@RequestBody Muser user) {
        int success = userService.register(user);
        if (success==1) {

            return Result.ok("注册成功");
        }
        if (success==0) {
            return Result.error("手机号已存在");
        }
        if (success==-1) {
            return Result.error("用户名重复");
        }
        if (success==-2) {
            return Result.error("手机号未再列表中");
        }
        return Result.error("注册失败，请重新尝试");
    }
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody Muser user) {
        Muser loginUser = userService.login(user.getPhone(), user.getPassword());
        if (loginUser != null) {
            StpUtil.login(loginUser.getId());
            return Result.data(StpUtil.getTokenInfo());
        }
        return Result.error("登录失败");
    }
    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/getInfo")
    public Result getInfo() {
        Long userId = UserUtils.getCurrentLoginId();
        Muser user = userService.getById(userId);
        return Result.data(user);
    }
    /**
     *  更新用户名字
     */
    @PostMapping("/updateName")
    public Result updateName(@RequestBody Muser user) {
        LambdaQueryWrapper<Muser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Muser::getNickname,user.getNickname());
        if (userService.getOne(lambdaQueryWrapper)!=null) {
            return Result.error("昵称已存在");
        }
        Long userId = UserUtils.getCurrentLoginId();
        Muser oldUser = userService.getById(userId);
        oldUser.setNickname(user.getNickname());
        boolean update = userService.updateById(oldUser);
        if (update) {
            return Result.ok("更新成功");
        }
        return Result.error("更新失败");
    }


}
